import 'package:flutter/material.dart';

class GlobalKeyPage extends StatefulWidget {
  const GlobalKeyPage({super.key});

  @override
  State<GlobalKeyPage> createState() => _GlobalKeyPageState();
}

class _GlobalKeyPageState extends State<GlobalKeyPage> {
  List<Widget> _list = [];
  final GlobalKey _globalKey1 = GlobalKey();
  final GlobalKey _globalKey2 = GlobalKey();
  final GlobalKey _globalKey3 = GlobalKey();

  @override
  void initState() {
    super.initState();
    _list = [
      //注意常量没法改变
      //1.可以保存状态   2.排序
      _BoxState(color: Colors.red, key: _globalKey1),
      _BoxState(
        color: Colors.yellow,
        key: _globalKey2, //唯一值  每次执行随机生成
      ),
      _BoxState(
        color: Colors.blue,
        key: _globalKey3, //传入一个对象
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    // print(MediaQuery.of(context).orientation);
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _list.shuffle(); //打乱list顺序
          });
        },
        child: Icon(Icons.refresh),
      ),
      appBar: AppBar(title: Text('GlobalKey全局key')),
      body: Center(
        child: MediaQuery.of(context).orientation == Orientation.portrait
            ? Column(
                spacing: 20,
                mainAxisAlignment: MainAxisAlignment.center,
                children: _list,
              )
            : Row(
                spacing: 20,
                mainAxisAlignment: MainAxisAlignment.center,
                children: _list,
              ),
      ),
    );
  }
}

class _BoxState extends StatefulWidget {
  final double width;
  final double height;
  final Color color;
  // final Key key;
  _BoxState({
    super.key,
    this.width = 100,
    this.height = 100,
    this.color = Colors.red,
  });

  @override
  State<_BoxState> createState() => __BoxStateState();
}

class __BoxStateState extends State<_BoxState> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: widget.height,
      // color: widget.color,
      child: ElevatedButton(
        onPressed: () {
          setState(() {
            _count++;
          });
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: widget.color,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
        ),
        child: Text(
          '$_count',
          style: Theme.of(context).textTheme.headlineMedium,
        ),
      ),
    );
  }
}
